package org.atlantis.datasink.utils;

import java.lang.management.ManagementFactory;

import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.atlantis.datasink.mx.INamedMBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class JMXHelper {

	private static final Logger log = LoggerFactory.getLogger(JMXHelper.class);

	public static boolean registerMBean(INamedMBean mbean) {
		try {
			MBeanServer mbServ = ManagementFactory.getPlatformMBeanServer();
			synchronized (mbServ) {
				ObjectName name = new ObjectName(mbean.getMBeanName());
				if (mbServ.isRegistered(name)) mbServ.unregisterMBean(name);
				mbServ.registerMBean(mbean, name);
			}
			return true;
		} catch (Exception e) {
			log.error("Register mbean error.", e);
		}
		return false;
	}

	public static boolean unregisterMBean(INamedMBean mbean) {
		try {
			MBeanServer mbServ = ManagementFactory.getPlatformMBeanServer();
			synchronized (mbServ) {
				ObjectName name = new ObjectName(mbean.getMBeanName());
				if (mbServ.isRegistered(name)) mbServ.unregisterMBean(name);
			}
			return true;
		} catch (Exception e) {
			log.error("UnRegister mbean error.", e);
		}
		return false;
	}

	private JMXHelper() {
		throw new UnsupportedOperationException();
	}
}
